<?php

/*

can handle creation, deletion, trashing, modifing of forms created by the spFormDatabase

*/

class spPageFormDatabaseManager extends spPage
{
	private $param;

	// no param in constructor because wordpress creates an instance of this
	public function __construct()
	{
		parent::__construct();
	}
	
	protected function setParam( $param )
	{
		// create defaults if not supplied
		$this->param = array_merge(
			array(
				"heading"			=> "",
				"heading_img"		=> ""
			),
			$param==null?array():$param	
		);
	}
	
	protected function showForm( $id, $dbClass, $title="" )
	{
		$database		= new $dbClass( $id );
		$formBuilder 	= $database->createFormBuilder();
		
		// this allows use to setup default values using $_REQUEST
		$database->updateFromRequest();
		
		$form = new spForm(array(
			"method" => "post"
		));
		parent::addChild( $form );
		
		$buttons = array();
		
		$buttons[] = array(
			"name"	=> "buttonsave",
			"value" => "save"
		);
		
		if ( $id )
		{
			$buttons[] = array(
				"name" => "buttontrash",
				"value" => "trash"
			);
			
			$buttons[] = array(
				"name" => "buttondelete",
				"value" => "delete"
			);
		}
		
		$dlg = spDialog2::create( array(
			"title" 		=> $title,
			"use_submit"	=> true,
			"buttons" 		=> $buttons
		));
		$dlg->addStyle( "width", "500px" );
		$dlg->addChild( $formBuilder );
		$form->addChild( $dlg );
	}
	
	protected function saveForm( $id, $dbClass )
	{
		$database = new $dbClass( $id );
		$database->updateFromRequest();
		$ret = $database->save();
		if ( !$ret )
		{
			$errors = $database->getFormErrors();
			echo $errors;
		}
		
		return $ret;
	}

	protected function deleteData( $id, $dbClass )
	{
		$db = new $dbClass( $id );
		if ( !$db->delete() )
			return false;
		
		return true;
	}
	
	protected function trashData( $id, $dbClass )
	{
		$db = new $dbClass( $id );
		if ( !$db->trash() )
			return false;
		
		return true;
	}
	
	public function actionDefault()
	{
	}

	public function actionSave()
	{
	}

	public function actionTrash()
	{
	}

	public function actionDelete()
	{
	}
	
	public function render()
	{
		parent::spRenderDefaults();
		parent::spRenderHeading( $this->param["heading"], $this->param["heading_img"] );

		if ( isset($_REQUEST["buttonsave"]) )
			$this->actionSave();
		else if ( isset($_REQUEST["buttontrash"]) )
			$this->actionTrash();
		else if ( isset($_REQUEST["buttondelete"]) )
			$this->actionDelete();
		else
			$this->actionDefault();
		
		parent::render();
	}
}

?>